package com.caifu.service;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.caifu.bean.PageDo;
import com.caifu.bean.Result;
import com.caifu.bean.ResultUtil;
import com.caifu.controller.AbstractController;
import com.caifu.enums.LabelTypeEnum;
import com.caifu.mapper.SysOrganizationMapper;
import com.caifu.mapper.SysUserMapper;
import com.caifu.mapper.YsLabelMapper;
import com.caifu.mapper.YsShopMapper;
import com.caifu.pojo.SysOrganization;
import com.caifu.pojo.YsLabel;
import com.caifu.pojo.YsShop;
import com.caifu.util.CheckUtil;
import com.caifu.util.Util;
import com.caifu.vo.ShopPageVO;
import com.caifu.vo.label.SaveMsLabelVO;
import com.caifu.vo.label.UpdateMsLabelVO;
import org.springframework.beans.BeanUtils;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.Resource;
import java.time.LocalDate;
import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;
import java.time.temporal.TemporalAdjusters;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Date;
import java.util.List;

/**
 * ClassName : LabelService
 *
 * @author :  szt
 * @description ：
 * @date : 2021-03-08 10:49
 */
@Service
public class LabelService extends AbstractController {

    @Resource
    private YsLabelMapper ysLabelMapper;
    @Resource
    private SysOrganizationMapper sysOrganizationMapper;
    @Resource
    private SysUserMapper sysUserMapper;

    /**
     * 获取所有标签
     *
     * @return Result
     */
    public Result<Object> getLabelType() {
        QueryWrapper<YsLabel> queryWrapper = new QueryWrapper<>();
        queryWrapper.and(wrapper -> wrapper.isNull("PID").or().eq("PID", ""));
        queryWrapper.eq("STATUS", "1");
        queryWrapper.orderByAsc("SORT");
        queryWrapper.orderByAsc("ID");
        List<YsLabel> msLabelList = ysLabelMapper.selectList(queryWrapper);
        return ResultUtil.getDataSuccess(msLabelList);
    }

    /**
     * 获取标签列表 分页
     *
     * @return Result
     */
    public Result<Object> getLabelListByLabelCodePagination(String labelCode, Integer currentPage, Integer pageSize) {
        if (Util.isNull(labelCode)) {
            return ResultUtil.error();
        }
        IPage<YsLabel> page = new Page<>(currentPage, pageSize);
        page.descs();
        QueryWrapper<YsLabel> msLabelQueryWrapper = new QueryWrapper<>();
        if (Util.isNotNull(labelCode)) {
            msLabelQueryWrapper.eq("PID", labelCode);
            msLabelQueryWrapper.ne("STATUS", "9");
        }
        ysLabelMapper.selectPage(page, msLabelQueryWrapper);

        return ResultUtil.getPageDataSuccess(new PageDo<>(Long.parseLong(currentPage + ""), Long.parseLong(pageSize + ""), Integer.parseInt(page.getTotal() + ""), page.getRecords()));
    }


    /**
     * 添加标签
     * @param saveMsLabelVO
     * @return
     */
    public Result<Object> addLabel(SaveMsLabelVO saveMsLabelVO) {
        if (Util.isNull(saveMsLabelVO.getParentCode())) {
            return ResultUtil.errorMsg("标签类型不能空");
        }
        int labelNameSize = 20;
        if (Util.isNull(saveMsLabelVO.getLabelName())) {
            return ResultUtil.errorMsg("标签名称不能为空");
        } else if (saveMsLabelVO.getLabelName().length() > labelNameSize) {
            return ResultUtil.errorMsg("标签名称不能超过20个字符");
        }

        //是否存在相同类型下名称相同的标签
        QueryWrapper<YsLabel> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("PID", saveMsLabelVO.getParentCode());
        queryWrapper.eq("LABEL_NAME", saveMsLabelVO.getLabelName());
        queryWrapper.eq("STATUS", "1");
        YsLabel isExistLabel = ysLabelMapper.selectOne(queryWrapper);
        if (Util.isNotNull(isExistLabel)) {
            return ResultUtil.errorMsg("此名称已被使用！");
        }
        //是否存在此种类型的标签 labelCode判断
        YsLabel isExistLabelType = ysLabelMapper.selectById(saveMsLabelVO.getParentCode());
        if (Util.isNull(isExistLabelType)) {
            return ResultUtil.errorMsg("不存在此标签类型");
        }
        //保存标签
        YsLabel ysLabel = new YsLabel();
        BeanUtils.copyProperties(saveMsLabelVO, ysLabel);
        String newLabelCode = ysLabelMapper.getMaxLabelCode(saveMsLabelVO.getParentCode());
        if (Util.isNull(newLabelCode)) {
            newLabelCode = saveMsLabelVO.getParentCode() + "01";
        } else {
            newLabelCode = String.valueOf(new Integer(newLabelCode) + 1);
        }
        ysLabel.setId(Integer.parseInt(newLabelCode));
        ysLabel.setPid(saveMsLabelVO.getParentCode());
        ysLabel.setCreatedTime(new Date());
        ysLabel.setStatus("1");
        ysLabel.setIsPreinstall("0");
        ysLabel.setSort(1L);
        ysLabelMapper.insert(ysLabel);
        return ResultUtil.success();
    }

    /**
     * 修改标签
     *
     * @param updateMsLabelVO vo
     * @return Result
     */
    public Result<Object> updateLabel(UpdateMsLabelVO updateMsLabelVO) {

        if (Util.isNull(updateMsLabelVO.getLabelCode())) {
            return ResultUtil.errorMsg("标签Code不能为空");
        }
        int labelNameSize = 20;
        if (Util.isNull(updateMsLabelVO.getLabelName())) {
            return ResultUtil.errorMsg("标签名称不能为空");
        } else if (updateMsLabelVO.getLabelName().length() > labelNameSize) {
            return ResultUtil.errorMsg("标签名称不能超过20个字符");
        }

        YsLabel ysLabel = ysLabelMapper.selectById(updateMsLabelVO.getLabelCode());
        if (Util.isNull(ysLabel)) {
            return ResultUtil.errorMsg("无法查询到此条记录");
        }

        //是否存在相同类型下名称相同的标签
        QueryWrapper<YsLabel> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("PID", updateMsLabelVO.getParentCode());
        queryWrapper.eq("LABEL_NAME", updateMsLabelVO.getLabelName());
        queryWrapper.ne("ID", updateMsLabelVO.getLabelCode());
        queryWrapper.eq("STATUS", "1");
        YsLabel isExistLabel = ysLabelMapper.selectOne(queryWrapper);
        if (Util.isNotNull(isExistLabel)) {
            return ResultUtil.errorMsg("此名称已被使用！");
        }

        ysLabel.setLabelName(updateMsLabelVO.getLabelName());
        ysLabelMapper.updateById(ysLabel);
        return ResultUtil.success();
    }



    /**
     * 获取 所有的 orgId 逗号分隔
     *
     * @param orgId orgId
     * @return String
     */
    private String getOrgIds(String orgId) {
        SysOrganization organization = sysOrganizationMapper.selectById(orgId);
        getChildOrganization(organization);
        //获取全部 orgId
        List<String> orgList = new ArrayList<>();
        orgList.add(organization.getId() + "");
        if (CheckUtil.isNotNull(organization.getChildren())) {
            getOrgList(orgList, organization.getChildren());
        }
        return String.join(",", orgList);
    }

    /**
     * 查询下面的所有组织架构
     *
     * @param organization organization
     */
    private void getChildOrganization(SysOrganization organization) {

        QueryWrapper<SysOrganization> organizationQueryWrapper = new QueryWrapper<>();
        organizationQueryWrapper.eq("pid", organization.getId());
        organizationQueryWrapper.eq("status", "1");
        List<SysOrganization> orgList = sysOrganizationMapper.selectList(organizationQueryWrapper);
        if (CheckUtil.isNotNull(orgList) && orgList.size() > 0) {
            orgList.forEach(this::getChildOrganization);
        }
        organization.setChildren(orgList);
    }

    /**
     * 删除标签
     *
     * @param labelCode 标签Code
     * @return Result
     */
    public Result<Object> deleteLabel(String labelCode) {

        if (Util.isNull(labelCode)) {
            return ResultUtil.errorMsg("标签Code 不能为空");
        }
        YsLabel ysLabel = ysLabelMapper.selectById(labelCode);
        if (Util.isNull(ysLabel)) {
            return ResultUtil.errorMsg("无法查询到此条记录");
        }
        ysLabel.setStatus("9");
        ysLabelMapper.updateById(ysLabel);
        return ResultUtil.success();
    }

    /**
     * 启动|关闭标签
     *
     * @param labelCode 标签Code
     * @return Result
     */
    public Result<Object> updateLabelState(String labelCode, String state) {

        if (Util.isNull(labelCode)) {
            return ResultUtil.errorMsg("标签Code 不能为空");
        }
        YsLabel ysLabel = ysLabelMapper.selectById(labelCode);
        if (Util.isNull(ysLabel)) {
            return ResultUtil.errorMsg("无法查询到此条记录");
        }
        ysLabel.setStatus(state);
        ysLabelMapper.updateById(ysLabel);
        return ResultUtil.success();
    }

    /**
     * 获取 组织架构下的  全部 orgId
     *
     * @param orgList      orgList
     * @param organization organization
     */
    private void getOrgList(List<String> orgList, List<SysOrganization> organization) {
        organization.forEach(org -> {
            orgList.add(org.getId() + "");
            if (CheckUtil.isNotNull(org.getChildren())) {
                getOrgList(orgList, org.getChildren());
            }
        });
    }

    /**
     * 获取 组织架构下的  全部 orgId
     *
     * @param orgList      orgList
     * @param organization organization
     */
    private void getOrgListTwo(List<String> orgList, List<SysOrganization> organization) {
        organization.forEach(org -> {
            orgList.add(org.getId() + "");
            if (CheckUtil.isNotNull(org.getSysOrganizations())) {
                getOrgListTwo(orgList, org.getSysOrganizations());
            }
        });
    }


    /**
     * id 获取 标签 names
     *
     * @param labelList labelList
     * @param labelIds  labelIds
     * @return return
     */
    private String getLabelNames(List<YsLabel> labelList, String labelIds) {
        String[] arr = labelIds.split(",");
        String labelNames = "";
        for (String s : arr) {
            if (CheckUtil.isNotNull(s)) {
                for (YsLabel label : labelList) {
                    if (label.getId().equals(Integer.parseInt(s))) {
                        if (CheckUtil.isNotNull(labelNames)) {
                            labelNames += "," + label.getLabelName();
                        } else {
                            labelNames += label.getLabelName();
                        }
                    }
                }
            }
        }
        return labelNames;
    }


    /**
     * 获取标签
     *
     * @param pid pid 父节点
     * @return List
     */
    public List<YsLabel> getYsLabelList(String pid) {
        QueryWrapper<YsLabel> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("pid", pid);
        queryWrapper.eq("status", "1");
        return ysLabelMapper.selectList(queryWrapper);
    }


}
